#include "service.h"

#include <chrono>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <string>
#include <thread>

namespace netaos {
namespace nosal {
namespace demo {
namespace svc {

Service::Service(const char *name)
    : name_(name), running_state_(RunningStates::kRunning) {
    std::cout << "Initializing Service.";
    Initialize();
}

Service::~Service() {
    std::cout << "Service exits.";
}

int Service::Run(const char *name) noexcept {
    try {
        std::cout << "Service uses name" << name;

        Service instance(name);

        std::cout << "Service is running.";

        instance.Run();

        return EXIT_SUCCESS;
    } catch (const std::exception &ex) {
        std::cerr << "Caught exception:" << ex.what();
    } catch (...) {
        std::cerr << "Caught unknown exception";
    }

    return EXIT_FAILURE;
}

void Service::Run() {
    std::cout << "Performing initial switch to Machine State Startup.";

    while (RunningStates::kRunning == running_state_) {
        std::this_thread::sleep_for(std::chrono::seconds(1));
        // std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }

    std::cout << "Service is stopping.";
}

void Service::Initialize() {
    std::cout << "Start of Service initialization.";

    std::cout << "Initialization finished";
}

}  // namespace svc
}  // namespace demo
}  // namespace nosal
}  // namespace netaos
